package group.cyfc.studygo.service;

import group.cyfc.studygo.dao.GatewayRepository;
import group.cyfc.studygo.dao.UserRecordRepository;
import group.cyfc.studygo.dao.UserRepository;
import group.cyfc.studygo.dto.JsonResult;
import group.cyfc.studygo.entity.Gateway;
import group.cyfc.studygo.entity.User;
import group.cyfc.studygo.entity.UserRecord;
import group.cyfc.studygo.util.SnowflakeIdWorker;
import group.cyfc.studygo.vo.GatewayVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author Vonlin
 */
@Service
public class GatewayService {

    @Autowired
    private GatewayRepository gatewayRepository;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserRecordRepository userRecordRepository;

    /**
     * 用户可选关卡列表
     * @param username
     * @param grade
     * @param subject
     * @return
     */
    public JsonResult getGateways(String username,String grade,String subject){
        Boolean is_del = false;
        User user = userRepository.findUserByUsernameAndIsDel(username,is_del);
        if(user==null){
            return new JsonResult<>().clientError(HttpStatus.UNPROCESSABLE_ENTITY,"用户不存在",username);
        }
        UserRecord userRecord = userRecordRepository.findByUserIdAndGradeAndSubjectAndIsDel(
                user.getId(),grade,subject,is_del);
        if(userRecord==null){
            Gateway gateway = gatewayRepository.findGatewayByGradeAndSubjectAndNumberAndIsDel(grade,subject,1,is_del);
            if(gateway==null){ return new JsonResult<>().serverError("不存在该类型关卡",grade+subject); }
            GatewayVo gatewayVo = toGatewayVo(gateway);
            List<GatewayVo> list = new ArrayList<>();
            list.add(gatewayVo);
            return new JsonResult<>().ok("ok",list);
        }
        Gateway gateway = gatewayRepository.findGatewayByIdAndIsDel(userRecord.getGatewayId(),is_del);
        List<GatewayVo> resultList = new ArrayList<>(16);
        List<Gateway> list = null;
        if(gateway.getNumber().equals(getNumber(gateway.getGrade(),gateway.getSubject()))){
            list = gatewayRepository.getUserGateways(gateway.getGrade(),gateway.getSubject(),gateway.getNumber(),new Sort(Sort.Direction.ASC,"number"));
            for(Gateway gate :list){
                GatewayVo gatewayVo = toGatewayVo(gate);
                resultList.add(gatewayVo);
            }
        }else{
            list = gatewayRepository.getUserGateways(gateway.getGrade(),gateway.getSubject(),gateway.getNumber()+1,new Sort(Sort.Direction.ASC,"number"));
            for(Gateway gate :list){
                GatewayVo gatewayVo = toGatewayVo(gate);
                resultList.add(gatewayVo);
            }
        }
        return new JsonResult<>().ok("ok",resultList);
    }

    public JsonResult getGateway(String grade,String subject,Integer number){
        Gateway gateway = gatewayRepository.findGatewayByGradeAndSubjectAndNumberAndIsDel(grade,subject,number,false);
        if(gateway==null){
            return new JsonResult<>().clientError(HttpStatus.UNPROCESSABLE_ENTITY,"error",grade+"-"+subject+"-"+number);
        }
        GatewayVo gatewayVo = toGatewayVo(gateway);
        return new JsonResult<>().ok("ok",gatewayVo);
    }

    public JsonResult getAllGateways(String grade,String subject){
        List<Gateway> list = gatewayRepository.findAllByGradeAndSubjectAndIsDel(grade,subject,new Boolean(false));
        if(list==null){
            return new JsonResult().ok("ok");
        }else {
            List<GatewayVo> resultList = new ArrayList<>();
            for(Gateway gateway:list){
                GatewayVo gatewayVo = toGatewayVo(gateway);
                resultList.add(gatewayVo);
            }
            return new JsonResult<>().ok("ok",resultList);
        }
    }

    /**
     * 获取对应类型关卡数目
     * @param grade
     * @param subject
     * @return
     */
    public Integer getNumber(String grade,String subject){
        return gatewayRepository.getNumber(grade,subject);
    }

    public List<String> getPaperIds(String grade,String subject){ return gatewayRepository.getPaperIdByGradeAndSubject(grade,subject); }

    public JsonResult changeGateway(GatewayVo gatewayVo){
        Gateway gateway = gatewayRepository.findByIdAndIsDel(Long.valueOf(gatewayVo.getId()),false);
        if(gateway==null){
            return new JsonResult<>().clientError(HttpStatus.UNPROCESSABLE_ENTITY,"error",gatewayVo.getId());
        }
        gatewayRepository.changeGateway(Long.valueOf(gatewayVo.getId()),Long.valueOf(gatewayVo.getPaperId()));
        return new JsonResult().ok("ok");
    }

    /**
     * 保存关卡信息
     * @param gatewayVo
     */
    public JsonResult  saveGateway(GatewayVo gatewayVo){
        Gateway gate = gatewayRepository.findGatewayByGradeAndSubjectAndNumberAndIsDel(
                gatewayVo.getGrade(),gatewayVo.getSubject(),gatewayVo.getNumber(),false);
        if(gate==null){
            Gateway gateway = new Gateway();
            BeanUtils.copyProperties(gatewayVo,gateway);
            gateway.setPaperId(Long.valueOf(gatewayVo.getPaperId()));
            System.out.println(gateway);
            gateway.setId(snowflakeIdWorker.nextId());
            gateway.setCreateBy(1L);
            gateway.setCreateAt(new Date());
            gateway.setUpdateBy(1L);
            gateway.setUpdateAt(new Date());
            gatewayRepository.save(gateway);
            return new JsonResult().ok("ok");
        }else {
            return new JsonResult<>().clientError(HttpStatus.UNPROCESSABLE_ENTITY,"error",gatewayVo);
        }
    }

    /**
     * 删除关卡
     * @param gatewayVo
     */
    public JsonResult deleteGateway(GatewayVo gatewayVo){
        Gateway gateway = gatewayRepository.findGatewayByIdAndIsDel(Long.valueOf(gatewayVo.getId()),new Boolean(false));
        if(gateway==null){
            return new JsonResult<>().clientError(HttpStatus.UNPROCESSABLE_ENTITY,"关卡已删除或不存在",gatewayVo.getId());
        }
        gatewayRepository.deleteGateway(gateway.getId());
        gatewayRepository.updateGatewayNumbers(gateway.getGrade(),gateway.getSubject(),gateway.getNumber());
        return new JsonResult().ok("ok");
    }

    /**
     * 将gateway实体对象转化成Vo对象
     * @param gateway
     * @return
     */
    private GatewayVo toGatewayVo(Gateway gateway){
        GatewayVo gatewayVo = new GatewayVo();
        BeanUtils.copyProperties(gateway,gatewayVo);
        if(gateway.getPaperId()!=null){
            gatewayVo.setPaperId(gateway.getPaperId().toString());
        }
        gatewayVo.setId(gateway.getId().toString());
        return gatewayVo;
    }
}
